package com.errol.batchprocessor.payroll.advisorimpl.common.multiemployeeinbatch;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.renjia.constant.Constant;
import com.renjia.dao.BusPayrollRecordDetailMapper;
import com.renjia.dao.BusPayrollRecordMapper;
import com.renjia.entity.BusPayrollRecordDetail;
import com.renjia.enums.PayrollDetailValidateStatusEnum;
import com.renjia.enums.SwitchEnum;
import com.renjia.properties.SpecialCustomerProperties;
import com.renjia.service.generic.log.LogService;
import com.renjia.service.generic.support.payroll.PayrollAmountSupportService;
import com.renjia.service.module.employeeaddition.advisorimpl.EmployeeAdvisorTypeEnum;
import com.renjia.service.module.employeeaddition.advisorimpl.payroll.payload.PayrollEmployeeBatchPayload;
import com.renjia.service.module.employeeaddition.advisorimpl.payroll.payload.PayrollEmployeePiecePayload;
import com.renjia.service.module.employeeaddition.advisorimpl.payroll.payload.PayrollEmployeeSinglePayload;
import com.renjia.service.module.payroll.advisor.verify.PayrollVerifySingleProcessAdvisor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 单个编辑不校验人员重复处理
 */
@Service
public class PayLimitManageAdvisorImpl extends PayLimitImportAdvisorImpl implements PayrollVerifySingleProcessAdvisor {
    private final PayrollAmountSupportService payrollAmountSupportService;
    private final LogService logService;
    private final BusPayrollRecordDetailMapper busPayrollRecordDetailMapper;
    private final BusPayrollRecordMapper busPayrollRecordMapper;

    public PayLimitManageAdvisorImpl(PayrollAmountSupportService payrollAmountSupportService,
                                     SpecialCustomerProperties specialCustomerProperties,
                                     BusPayrollRecordMapper busPayrollRecordMapper, LogService logService,
                                     BusPayrollRecordDetailMapper busPayrollRecordDetailMapper) {
        super(payrollAmountSupportService, specialCustomerProperties, logService);
        this.logService = logService;
        this.payrollAmountSupportService = payrollAmountSupportService;
        this.busPayrollRecordDetailMapper = busPayrollRecordDetailMapper;
        this.busPayrollRecordMapper = busPayrollRecordMapper;
    }


    @Override
    public boolean shallProcess(@NonNull PayrollEmployeeBatchPayload advisorPayload) {
        return EmployeeAdvisorTypeEnum.PAYROLL_RECORD_MANAGE == advisorPayload.getAdvisorTypeEnum()
                && SwitchEnum.OFF.getCode2().equals(advisorPayload.getCoreCustomerChannelMerchant().getAllowEmployeeRepeat());
    }

    @Override
    public int priority() {
        return 112;
    }

    @Override
    public boolean doExecuteOnEmployeeInfoSavedAtVerifyStage(PayrollEmployeeSinglePayload singlePayload, PayrollEmployeePiecePayload piecePayload, PayrollEmployeeBatchPayload batchPayload) {
        //5.2.0添加服务费小于0的过滤
        if (singlePayload.getSingleEntity().getShouldPayBrokerage().compareTo(BigDecimal.ZERO) < Constant.COMMON_ZERO) {
            singlePayload.getErrMsgList().add("服务费不能小于0");
            return false;
        }
        BigDecimal inFactPayAmount = getInFactPayAmount(singlePayload, piecePayload, batchPayload);
        BigDecimal monthlyUsedAmount = payrollAmountSupportService.getMonthlyUsedAmountOfEmployee(singlePayload.getCoreEmployee().getId(),
                singlePayload.getSingleEntity().getPayTime());
        BigDecimal allBatchAmount = null;
        //查询本批次已经验证通过的金额
        Wrapper<BusPayrollRecordDetail> wrapper = Condition.wrapper();
        wrapper.setSqlSelect("IFNULL(SUM(infact_pay_amount),0) as amount");
        wrapper.eq("batch_no", batchPayload.getBatchNo());
        wrapper.eq("document_number", singlePayload.getDocumentNumber());
        wrapper.eq("valid_status", PayrollDetailValidateStatusEnum.VALIDATE_PASS.getCode());
        wrapper.ne(StringUtils.isNotBlank(singlePayload.getSingleEntity().getId()), "id", singlePayload.getSingleEntity().getId());
        List<Map<String, Object>> list = busPayrollRecordDetailMapper.selectMaps(wrapper);
        if (list != null && list.size() > 0) {
            allBatchAmount = (BigDecimal) list.get(0).get("amount");
        } else {
            allBatchAmount = BigDecimal.ZERO;
        }
        boolean off = false;
        synchronized (this) {
            allBatchAmount = monthlyUsedAmount.add(allBatchAmount);
            if (allBatchAmount.add(inFactPayAmount).compareTo(batchPayload.getPayLimitPayload().getMonthLimitAmount()) > 0) {
                off = true;
            }
        }
        if (off) {
            singlePayload.getErrMsgList().add(String.format("当月最高限额：￥%s, 当月已发放：￥%s（不含当次）", batchPayload.getPayLimitPayload().getMonthLimitAmount(), monthlyUsedAmount));
            return false;
        } else {
            logService.debug("【人员导入批处理】【" + batchPayload.getBatchEntity().getBatchNo() + "】【" + singlePayload.getSingleEntity().getId() + "】月限额验证通过");
        }
        return true;
    }
}
